<h2>{@html __('publish / title') }</h2>

<PublishButton
    {published}
    {publishing}
    {publishStarted}
    {now}
    {progress}
    {unpublished}
    {unpublishing}
    redirectDisabled="{redirect_disabled}"
    needsRepublish="{needs_republish}"
    publishError="{publish_error}"
    publicVersion="{chart.publicVersion}"
    on:publish="publish()"
    on:unpublish="requestUnpublishConfirmation()"
/>

{#if published}
<ShareEmbed
    {pluginShareurls}
    {embedTemplates}
    pending="{publishing || unpublishing}"
    {shareurlType}
    {embedType}
    metadata="{chart.metadata}"
    id="{chart.id}"
    publicUrl="{chart.publicUrl}"
/>
{/if}

<ConfirmationModal
    ref:confirmationModal
    confirmButtonText="{__('publish / unpublish-confirmation / unpublish')}"
    confirmButtonIcon="undo"
    backButtonText="{__('publish / unpublish-confirmation / back')}"
    id="modalConfirmation"
    title="{__('publish / unpublish-confirmation / title')}"
    on:confirm="unpublish()"
>
    <p>{@html __('publish / unpublish-confirmation / explanation')}</p>
</ConfirmationModal>

<script>
    /* eslint camelcase: "off" */
    import PublishButton from '@datawrapper/controls/publish/PublishButtonControl.html';
    import { __ } from '@datawrapper/shared/l10n';
    import httpReq from '@datawrapper/shared/httpReq';
    import { trackEvent } from '@datawrapper/shared/analytics';

    import ConfirmationModal from '@datawrapper/controls/ConfirmationModal.html';
    import ShareEmbed from './ShareEmbed.html';

    let initial_auto_publish = true;

    export default {
        components: {
            PublishButton,
            ConfirmationModal,
            ShareEmbed
        },
        data() {
            return {
                chart: {
                    id: ''
                },
                embedTemplates: [],
                pluginShareurls: [],
                published: false,
                publishing: false,
                publishStarted: 0,
                unpublished: false,
                unpublishing: false,
                needs_republish: false,
                publish_error: false,
                auto_publish: false,
                progress: [],
                shareurlType: 'default',
                embedType: 'responsive',
                statusUrl: false,
                redirect_disabled: false
            };
        },

        computed: {
            publishWait({ publishStarted, now }) {
                return publishStarted > 0 ? now - publishStarted : 0;
            }
        },
        helpers: { __ },
        methods: {
            publish() {
                const me = this;
                // wait another 100ms until the page is ready
                if (!window.chart.save) {
                    setTimeout(() => {
                        me.publish();
                    }, 100);
                    return;
                }
                const { chart } = me.get();

                me.set({
                    publishing: true,
                    publishStarted: new Date().getTime(),
                    now: new Date().getTime(),
                    progress: [],
                    unpublished: false,
                    publish_error: false
                });

                // update charts
                me.set({ chart });

                trackEvent('Chart Editor', 'publish');

                window.chart
                    .attributes(chart)
                    .save()
                    .then(() => {
                        this.set({
                            statusUrl: `/v3/charts/${chart.id}/publish/status/${chart.publicVersion}`
                        });
                        // publish chart
                        httpReq
                            .post(`/v3/charts/${chart.id}/publish`)
                            .then(() => {
                                httpReq.get(`/v3/charts/${chart.id}`).then(res => {
                                    trackEvent('Chart Editor', 'publish-success');
                                    me.publishFinished(res);
                                });
                            })
                            .catch(error => {
                                this.set({
                                    publish_error: error.message,
                                    publishing: false,
                                    progress: []
                                });
                                trackEvent('Chart Editor', 'publish-error', error.message);
                            });
                        setTimeout(() => {
                            const { publishing } = me.get();
                            if (publishing) me.updateStatus();
                        }, 1000);
                    });
            },

            unpublish() {
                const { chart } = this.get();

                this.set({
                    progress: [],
                    unpublishing: true,
                    needs_republish: false
                });

                httpReq
                    .post(`/v3/charts/${chart.id}/unpublish`)
                    .then(() => {
                        httpReq.get(`/v3/charts/${chart.id}`).then(chartUpdates => {
                            this.set({ chart: chartUpdates });
                            trackEvent('Chart Editor', 'unpublish-success');

                            // slow down visual response, reduces flickering:
                            setTimeout(() => {
                                this.set({
                                    published: false,
                                    unpublishing: false,
                                    unpublished: true
                                });
                            }, 1000);
                        });
                    })
                    .catch(error => {
                        this.set({ publish_error: error.message, unpublishing: false });
                        trackEvent('Chart Editor', 'unpublish-error', error.message);
                    });
            },

            requestUnpublishConfirmation() {
                this.set({ publish_error: null });
                this.refs.confirmationModal.open();
            },

            updateStatus() {
                const me = this;
                const { statusUrl } = me.get();
                if (!statusUrl) return;
                httpReq.get(statusUrl).then(res => {
                    this.set({
                        progress: res.progress || [],
                        now: new Date().getTime()
                    });
                    const { publishing } = this.get();
                    if (publishing) {
                        setTimeout(() => {
                            this.updateStatus();
                        }, 500);
                    }
                });
            },

            publishFinished(chartInfo) {
                this.set({
                    progress: ['done'],
                    published: true,
                    publishStarted: 0,
                    needs_republish: false,
                    publishing: false,
                    chart: chartInfo
                });

                window.parent.postMessage(
                    {
                        source: 'datawrapper',
                        type: 'chart-publish',
                        chartId: chartInfo.id
                    },
                    '*'
                );

                window.chart.attributes(chartInfo);
            }
        },
        onstate({ changed, current }) {
            const userDataReady = window.dw && window.dw.backend && window.dw.backend.setUserData;
            if (changed.embedType && userDataReady) {
                const data = window.dw.backend.__userData;
                if (!current.embedType || !data) return;
                data.embed_type = current.embedType;
                window.dw.backend.setUserData(data);
            }
            if (changed.shareurl_type && userDataReady) {
                const data = window.dw.backend.__userData;
                if (!current.shareurlType || !data) return;
                data.shareurl_type = current.shareurlType;
                window.dw.backend.setUserData(data);
            }
            if (changed.published) {
                window.document
                    .querySelector('.dw-create-publish .publish-step')
                    .classList[current.published ? 'add' : 'remove']('is-published');
            }
            if (changed.auto_publish) {
                if (current.auto_publish && initial_auto_publish) {
                    this.publish();
                    initial_auto_publish = false;
                    window.history.replaceState('', '', window.location.pathname);
                }
            }
        }
    };
</script>
